package com.bosssoft.trainee.service.imp;

import com.auth0.jwt.JWT;
import com.bosssoft.trainee.service.TokenService;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author liuqiang
 * @date 2022/7/13 16:55
 */
@Service
public class TokenServiceImp implements TokenService {

    public String getUserId() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        String token = "";
        if (requestAttributes != null) {
            HttpServletRequest request = requestAttributes.getRequest();
            token = request.getHeader("token");// 从 http 请求头中取出 token
            return JWT.decode(token).getAudience().get(0);
        } else {
            return "0";
        }
    }
}
